package com.haixiaoke.smartLock.huixiangjia;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.haixiaoke.domain.LockCommandLog;
import com.haixiaoke.domain.LockInfoLog;
import com.haixiaoke.domain.LockUnlockLog;
import com.haixiaoke.domain.LockWarningLog;
import com.haixiaoke.service.impl.LockCommandLogServiceImpl;
import com.haixiaoke.service.impl.LockInfoLogServiceImpl;
import com.haixiaoke.service.impl.LockUnlockLogServiceImpl;
import com.haixiaoke.service.impl.LockWarningLogServiceImpl;
import com.haixiaoke.vo.HuiXiangJiaCallBackData;
import com.haixiaoke.vo.HuiXiangJiaLogKeys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * 慧享佳-事件回调处理
 *
 * @Author xiaolong
 * @Date 2024/08/16
 */
@Slf4j
@Service
public class SmartLockHxjLogEventHandleService {

    @Autowired
    private LockInfoLogServiceImpl lockInfoLogService;
    @Autowired
    private LockWarningLogServiceImpl lockWarningLogService;
    @Autowired
    private LockCommandLogServiceImpl lockCommandLogService;
    @Autowired
    private LockUnlockLogServiceImpl lockUnlockLogService;


    /**
     * 开锁日志回调
     *
     * @param huiXiangJiaCallBackData
     * @return
     */
    public Map<String, Object> lockOpenLog(HuiXiangJiaCallBackData huiXiangJiaCallBackData) {
        Map<String, Object> resultMap = new HashMap<>();
        if (huiXiangJiaCallBackData.getLogType() == null) {
            resultMap.put("code", 500);
            resultMap.put("message", "参数不全");
        }
        try {
            // 开门记录
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Long createTime = huiXiangJiaCallBackData.getCreateTime() * 1000;
            String format = sdf.format(createTime);
            switch (huiXiangJiaCallBackData.getLogType()) {
                case 4:   // 开锁
                    HuiXiangJiaLogKeys logKeys = huiXiangJiaCallBackData.getLogKeys().get(0);
                    LockUnlockLog lockUnlockLog = new LockUnlockLog();
                    lockUnlockLog.setLockSn(huiXiangJiaCallBackData.getRoomId());
                    // 将开锁状态转换为系统开锁类型
                    lockUnlockLog.setUnlockType(hxjOpenTypeConvert(logKeys.getKeyType()));
                    lockUnlockLog.setUnlockState(0);
                    lockUnlockLog.setUnlockTime(DateUtil.parse(format));
                    lockUnlockLog.setIdentification(logKeys.getKeyId());
                    lockUnlockLog.setBrandId(LockWarningLog.HXJ_BRAND_ID);
                    lockUnlockLog.setLockState(LockUnlockLog.LOCK_STATE_ONLINE);
                    lockUnlockLog.setBrandName(LockWarningLog.HXJ_BRAND_NAME);
                    lockUnlockLog.setModelId(LockWarningLog.HXJ_BRAND_MODEL_ID);
                    lockUnlockLog.setModelName(LockWarningLog.HXJ_BRAND_MODEL_NAME);
                    lockUnlockLog.setCreateTime(new Date());
                    lockUnlockLogService.insertLockUnlockLog(lockUnlockLog);
                    break;
                case 1:     // 强拆报警
                case 2:     // 非法操作报警（错误次数超限等）
                case 3:     // 低电量报警
                case 7:     // 胁迫开锁
                    LockWarningLog lockWarningLog = new LockWarningLog();
                    lockWarningLog.setLockSn(huiXiangJiaCallBackData.getRoomId());
                    // 将告警状态转换为系统告警类型
                    lockWarningLog.setWarningType(hxjWarnTypeConvert(huiXiangJiaCallBackData.getLogType()));
                    lockWarningLog.setCreateTime(DateUtil.parse(format));
                    lockWarningLog.setBrandId(LockWarningLog.HXJ_BRAND_ID);
                    lockWarningLog.setBrandName(LockWarningLog.HXJ_BRAND_NAME);
                    lockWarningLog.setModelId(LockWarningLog.HXJ_BRAND_MODEL_ID);
                    lockWarningLog.setModelName(LockWarningLog.HXJ_BRAND_MODEL_NAME);
                    lockWarningLogService.insertLockWarningLog(lockWarningLog);
                    break;
                case 8:    //同步授权记录
                    HuiXiangJiaLogKeys huiXiangJiaLogKeys = huiXiangJiaCallBackData.getLogKeys().get(1);
                    LockCommandLog lockCommandLog = new LockCommandLog();
                    // 将密码类型转换为系统命令类型
                    lockCommandLog.setCommandType(hxjPasswordConvert(huiXiangJiaLogKeys.getKeyType()));
                    lockCommandLog.setLockSn(huiXiangJiaCallBackData.getRoomId());
                    lockCommandLog.setCallbackState(0);
                    lockCommandLog.setBrandId(LockWarningLog.HXJ_BRAND_ID);
                    lockCommandLog.setBrandName(LockWarningLog.HXJ_BRAND_NAME);
                    lockCommandLog.setModelId(LockWarningLog.HXJ_BRAND_MODEL_ID);
                    lockCommandLog.setModelName(LockWarningLog.HXJ_BRAND_MODEL_NAME);
                    lockCommandLogService.insertLockCommandLog(lockCommandLog);
                    break;
            }

            resultMap.put("code", 200);
            resultMap.put("message", "success");
        } catch (Exception e) {
            log.error("慧享佳回调数据--开门回调数据异常：{}", e.getMessage(), e);
            resultMap.put("code", 500);
            resultMap.put("message", "系统异常");
        }
        return resultMap;
    }


    /**
     * 锁状态回调
     *
     * @param huiXiangJiaCallBackData
     * @return
     */
    public Map<String, Object> lockStateLog(HuiXiangJiaCallBackData huiXiangJiaCallBackData) {
        Map<String, Object> resultMap = new HashMap<>();
        if (huiXiangJiaCallBackData.getState() == null) {
            resultMap.put("code", 500);
            resultMap.put("message", "参数不全");
        }
        try {
            if (ObjectUtil.isNotEmpty(huiXiangJiaCallBackData)) {
                LockInfoLog lockInfoLog = new LockInfoLog();
                lockInfoLog.setBattery(huiXiangJiaCallBackData.getElectricNum());
                lockInfoLog.setInfoType(LockInfoLog.INFOTYPE_HEARTBEAT);
                lockInfoLog.setLockSn(huiXiangJiaCallBackData.getRoomId());
                lockInfoLog.setCreateTime(new Date());
                lockInfoLog.setBrandId(LockWarningLog.HXJ_BRAND_ID);
                lockInfoLog.setBrandName(LockWarningLog.HXJ_BRAND_NAME);
                lockInfoLog.setModelId(LockWarningLog.HXJ_BRAND_MODEL_ID);
                lockInfoLog.setModelName(LockWarningLog.HXJ_BRAND_MODEL_NAME);
                lockInfoLogService.insertLockInfoLog(lockInfoLog);
            }
            resultMap.put("code", 200);
            resultMap.put("message", "success");
        } catch (Exception e) {
            log.error("慧享佳回调数据--锁状态回调异常：{}", e.getMessage(), e);
            resultMap.put("code", 500);
            resultMap.put("message", "系统异常");
        }
        return resultMap;
    }

    /**
     * 将开锁状态转换为系统开锁类型
     *
     * @param openType
     * @return
     */
    private Integer hxjOpenTypeConvert(Integer openType) {
        /**
         * 慧享佳开锁钥匙类型
         * 2	密码
         * 4	卡片
         * 8	遥控
         * 32	机械钥匙
         * 64	人脸
         * 128	蓝牙
         */
        /**
         * 系统开锁类型:1：永久密码 2：指纹 3：临时密码 4：远程开锁 5：蓝牙开锁 6：cookie开锁 7：门卡开锁
         * 8- 撤防/布防 10：机械钥匙开门 11：反锁 12 - 门内开锁 13:装修密码 14:装修密码开锁失败 15:离线开锁 16:人脸开锁 17:胁迫报警
         */
        Integer type = null;
        switch (openType) {
            case 2:
                type = 3;
                break;
            case 4:
                type = 7;
                break;
            case 32:
                type = 10;
                break;
            case 64:
                type = 16;
                break;
            case 128:     // 蓝牙
            case 129:     // 蓝牙
                type = 5;
                break;
        }
        return type;
    }


    /**
     * 将告警状态转换为系统告警类型
     *
     * @param logType
     * @return
     */
    private Integer hxjWarnTypeConvert(Integer logType) {
        /**
         *  慧享佳告警类型
         * 1	强拆报警
         * 2	非法操作报警（错误次数超限等），系统已 锁定
         * 3	低电量报警
         * 7	胁迫开锁
         * 14	门未关好（假锁报警）
         * 15	未关门报警
         */
        /**
         * 告警类型: 1：撞击报警 2：低电量 3：撬锁报警 5：长时间未关
         * 6：蓝牙cookie错误 8：非法开门报警 9：密码错误自锁报警 10：假锁
         */
        Integer type = null;
        switch (logType) {
            case 1:
                type = 1;
                break;
            case 2:
                type = 9;
                break;
            case 3:
                type = 2;
                break;
            case 7:
                type = 8;
                break;
            case 14:
                type = 10;
                break;
            case 15:
                type = 5;
                break;
        }
        return type;
    }

    /**
     * 将密码类型转换为系统命令类型
     *
     * @param keyType
     * @return
     */
    private Integer hxjPasswordConvert(Integer keyType) {

        /**
         * 钥匙类型
         * 1	指纹
         * 2	密码
         * 4	卡片
         * 64	人脸
         */
        /**
         * 命令类型: 1:同步临时密码 2：同步成员密码 4：同步门卡 6：同步指纹 7:远程开锁 8:清空指令 9:清空指令(包含蓝牙密码) 10:同步人脸
         */
        Integer type = null;
        switch (keyType) {
            case 1:
                type = 6;
                break;
            case 2:
                type = 1;
                break;
            case 4:
                type = 4;
                break;
            case 64:
                type = 10;
                break;
        }
        return type;
    }
}
